<template>
    <div class="member-list-page">
      <el-divider>学生查询</el-divider>
      <div class="stu-list-area">
        <div class="action-buttons">
            <el-button type="primary" @click="showDialogSingle">添加学生</el-button>
            <el-button type="success" @click="gotoCourseStuManage">批量添加学生</el-button>
        </div>

        <el-table
            v-if="members.length"
            :data="members"
            stripe
            border
            max-height="80%"
            style="width: 100%;"
            >
            <el-table-column prop="id" label="用户 ID" width="100" />
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="createTime" label="注册时间" />
        </el-table>
        <div v-else class="no-data">正在加载或暂无成员...</div>

        <!-- 分页查询区 -->
        <div class="query-box">
            <el-form :inline="true" class="query-form">
                <el-form-item label="页码">
                    <el-input-number v-model="pageNum" :min="1" />
                </el-form-item>
                <el-form-item label="每页条数">
                    <el-input-number v-model="pageSize" :min="1" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="fetchPage">查询</el-button>
                </el-form-item>
            </el-form>
        </div>
      </div>
        
      <el-divider>学习进度查询</el-divider>
      <div class="learning-progress-area">
        <!-- 饼图容器 -->
        <div ref="chartRef" style="width: 600px; height: 400px;"></div>
    
        <!-- 学生列表悬浮窗 -->
        <el-dialog title="阶段学习学生列表" v-model="showTooltip" width="500px">
          <div class="tooltip-header">{{ activeSection }}学生列表</div>
          <el-divider></el-divider>
          <div class="student-grid">
            <div v-for="(student, index) in activeStudents" :key="index" class="student-item">
              {{ student.username }}
            </div>
          </div>
          <template #footer>
            <el-button type="success" @click="showTooltip = false">关闭</el-button>
          </template>
        </el-dialog>
      </div>
    </div>

    

    <!-- 添加学生对话框 -->
    <el-dialog title="添加学生" v-model="dialogVisible" width="500px">
      <el-form label-width="100px">
        <el-form-item label="学生姓名">
          <el-input class="searchSingle" v-model="studentName" placeholder="搜索学生姓名" />
          <el-button type="primary" @click="searchSingleName">搜索</el-button>
        </el-form-item>
        <el-form-item label="或学生邮箱">
          <el-input
            type="textarea"
            class="searchSingle"
            :rows="4"
            v-model="studentEmail"
            placeholder="搜索学生邮箱"
          />
          <el-button type="primary" @click="searchSingleEmail">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-divider></el-divider>
        <el-table
            v-if="searchedMembers.length"
            :data="searchedMembers"
            stripe
            border
            style="width: 100%;"
            @selection-change="handleSelectionChange"
            >
            <!-- 多选框列，用于选中一行 -->
            <el-table-column type="selection" width="55" />
            <el-table-column prop="id" label="用户 ID" width="100" />
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="createTime" label="注册时间" />
        </el-table>
        <!-- 分页查询区 -->
        <div class="query-box-liner">
          <el-form :inline="true" class="query-form">
            <el-form-item class="stuPage" label="页码">
              <el-input-number v-model="stuPageNum" :min="1" />
            </el-form-item>
            <el-form-item class="stuPage" label="每页条数">
              <el-input-number v-model="stuPageSize" :min="1" />
            </el-form-item>
          </el-form>
        </div>
      <el-divider></el-divider>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSingle">添加</el-button>
      </template>
    </el-dialog>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts';
import { useCookies } from 'vue3-cookies'
import { ElMessage } from 'element-plus';
import router from '@/router';

const { cookies } = useCookies()
const dialogVisible = ref(false); // 控制对话框显示

const members = ref([])
const pageNum = ref(1)
const pageSize = ref(10)

const courseID = ref(null)

const studentName = ref('')
const studentEmail = ref('')

// 选中行后保存的学生 ID
const studentIdSingle = ref('')
// 存储搜索结果列表
const searchedMembers = ref([])
const stuPageNum = ref(1)
const stuPageSize = ref(5)

// 图表相关引用
const chartRef = ref(null);
let chartInstance = null;

// 数据相关状态
const progressData = ref({
  stuList1: [],
  stuList2: [],
  stuList3: [],
  stuList4: []
});

// 悬浮窗相关状态
const showTooltip = ref(false);
const tooltipStyle = ref({});
const activeStudents = ref([]);
const activeSection = ref('');

onMounted(async () => {
  // 1. 从 Cookie 读取已选课程 ID
  const stored = cookies.get('selectedCourse')
  let courseId = null
  try {
    courseId = stored.id
    courseID.value = stored.id
  } catch {
    console.error('解析 selectedCourse 失败')
    return
  }

  try {
    // 2. 拉取课程成员列表
    const membersRes = await axios.get(`/api/course/members?pageNum=${pageNum.value}&pageSize=${pageSize.value}&courseID=${courseId}`)
    if (membersRes.data?.code !== 200) {
      ElMessage({ type: 'error', message: `查询成员失败` });
      throw new Error(membersRes.data.msg || '查询成员失败')
    }
    if (membersRes.data?.data.records.length <= 0) {
      ElMessage({ type: 'error', message: `不存在课程成员` });
      return
    }
    const list = membersRes.data.data.records  // [{ id, username }, ...]
    console.log(list)

    // 3. 并发获取每个成员的完整信息
    const detailPromises = list.map(async ({ id }) => {
      const userRes = await axios.get(`/api/customer/user/id?id=${id}`)
      if (userRes.data?.code !== 200) {
        console.warn(`获取用户 ${id} 信息失败：`, userRes.data.msg)
        return null
      }
      const d = userRes.data.data
      // 4. 过滤掉不展示的字段
      return {
        id:         d.id,
        username:   d.username,
        email:      d.email,
        createTime: d.createTime
      }
    })

    // 等待所有完成，并剔除 null
    members.value = (await Promise.all(detailPromises)).filter(x => x)
  } catch (e) {
    console.error(e)
    members.value = []
  }

  fetchProgressData();
})

function gotoCourseStuManage(){
  router.push({path : '/teacher/courseManage/courseStuAddMulti'})
}

// 清理
onBeforeUnmount(() => {
  if (chartInstance) chartInstance.dispose();
  window.removeEventListener('click', () => {});
});

function showDialogSingle(){
    studentEmail.value = '';
    studentName.value = '';
    dialogVisible.value = true;
}

async function submitSingle(){
    try{
        if(!studentIdSingle.value){
            ElMessage({ type: 'error', message: `请选择学生` });
            return
        }
        const membersRes = await axios.post(`/api/course/add-student`, {
            courseID: Number(courseID.value),
            studentID: Number(studentIdSingle.value),
        }, {
            headers: { 'Content-Type': 'multipart/form-data' }
        })
        if (membersRes.data?.code !== 200) {
            throw new Error(membersRes.data.msg || '查询成员失败')
        }
        studentIdSingle.value = null
        console.log(membersRes)
        ElMessage({ type: 'success', message: `添加成功` });
        dialogVisible = false;
    }catch(err){
        console.log(err)
    }
}

async function searchSingleName(){
    try{
        const membersRes = await axios.get(`/api/customer/user/page`, {
            params:{
                pageSize: 5,
                pageNum: 1,
                username: studentName.value,
                role: 0,
            }
        })
        if (membersRes.data?.code !== 200) {
            throw new Error(membersRes.data.msg || '查询成员失败')
        }
        if (membersRes.data?.data.records.length <= 0) {
            ElMessage({ type: 'error', message: `不存在课程成员` });
            return
        }
        const list = membersRes.data.data.records
        
        const detailPromises = list.map(async ({ id }) => {
            const userRes = await axios.get(`/api/customer/user/id?id=${id}`)
            if (userRes.data?.code !== 200) {
                console.warn(`获取用户 ${id} 信息失败：`, userRes.data.msg)
                return null
            }  
            const d = userRes.data.data
            // 4. 过滤掉不展示的字段
            return {
                id:         d.id,
                username:   d.username,
                email:      d.email,
                createTime: d.createTime
            }
        })

        // 等待所有完成，并剔除 null
        searchedMembers.value = (await Promise.all(detailPromises)).filter(x => x)
    } catch (e) {
        console.error(e)
        searchedMembers.value = []
    }
}

async function searchSingleEmail(){
    try{
        const membersRes = await axios.get(`/api/customer/user/email?email=${studentEmail.value}`)
        if (membersRes.data?.code !== 200) {
            ElMessage({ type: 'error', message: `查询学生失败` });
            throw new Error(membersRes.data.msg || '查询成员失败')
        }
        // 把返回的单条 data 放入数组，以填充表格
        searchedMembers.value = [membersRes.data.data]
        console.log(membersRes)
    }catch(err){
        ElMessage.error('网络错误，查询失败')
        console.log(err)
    }
}

/** 行选中变化时触发，把第一个选中行的 id 存入 studentIdSingle */
function handleSelectionChange(selection) {
  if (selection.length > 0) {
    studentIdSingle.value = selection[0].id
  } else {
    studentIdSingle.value = ''
  }
}

// 获取学习进度数据
const fetchProgressData = async () => {
  try {
    const response = await axios.get(`/api/chapter/courseprogress?courseID=${courseID.value}`)   
    const result = await response.data;
    if (result && result.code === 200) {
      progressData.value = result.data;
      initChart();
    }
  } catch (error) {
    console.error('获取进度数据失败:', error);
  }
};

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;
  
  // 销毁现有实例
  if (chartInstance) chartInstance.dispose();
  
  // 创建新实例
  chartInstance = echarts.init(chartRef.value);
  
  // 准备饼图数据
  const chartOption = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}人 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['0%~25%', '25%~50%', '50%~75%', '75%~100%']
    },
    series: [{
      name: '学习进度',
      type: 'pie',
      radius: '55%',
      data: [
        { value: progressData.value.stuList1.length, name: '0%~25%' },
        { value: progressData.value.stuList2.length, name: '25%~50%' },
        { value: progressData.value.stuList3.length, name: '50%~75%' },
        { value: progressData.value.stuList4.length, name: '75%~100%' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  };
  
  // 设置图表选项
  chartInstance.setOption(chartOption);
  
  // 绑定点击事件
  chartInstance.on('click', handleChartClick);
};

// 处理饼图点击事件
const handleChartClick = (params) => {
  console.log('click')
  if (params.componentType === 'series' && params.seriesType === 'pie') {
    const sectionIndex = params.dataIndex;
    const sections = ['stuList1', 'stuList2', 'stuList3', 'stuList4'];
    const sectionNames = ['0%~25%', '25%~50%', '50%~75%', '75%~100%'];
    
    // 获取对应阶段的学生
    activeStudents.value = progressData.value[sections[sectionIndex]];
    activeSection.value = sectionNames[sectionIndex];
    
    // 设置悬浮窗位置
    showTooltip.value = true;
    tooltipStyle.value = {
      left: `${params.event.event.pageX + 10}px`,
      top: `${params.event.event.pageY + 10}px`
    };
  }
};

</script>

<style scoped>
.member-list-page {
  padding: 24px;
  /* background: #f5f7fa; */
  min-height: 100vh;
}
.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-bottom: 16px;
}
.no-data {
  text-align: center;
  color: #909399;
  margin-top: 50px;
}
.searchSingle{
    width: 70%;
    margin-right:5%;
}
.stuPage{
    width: 40%;
}
.query-box-liner{
    margin-top: 10px;
}
.query-box{
    margin-top: 40px;
}
</style>

